<script lang="ts" setup>
import Condition from '@/components/Condition/index.vue'
import { ref, watch, reactive, onMounted, nextTick } from 'vue'
import axios from 'axios'
import { visoConfig } from './config'
import { ElMessage } from 'element-plus'
import { listDatabase } from '@/api/data-integrate/database'
import Form from '@/components/Form/index.vue'
import store from '@/store'
import { platformSave, platformUpdate } from '@/api/sys/platform'

import { getNodeName, getGraph, addNextLink } from '@/api/data-blood'

let tick = 0

const condition = reactive<P.conditionItem[]>([
	{
		dataIndex: 'node_type',
		type: 'select',
		data: [
			{
				label: '原表',
				value: 1
			},
			{
				label: '接入任务',
				value: 2
			},
			{
				label: 'ods表',
				value: 3
			},
			{
				label: 'ods视图',
				value: 4
			},
			{
				label: 'flink作业',
				value: 5
			},
			{
				label: '调度任务datax',
				value: 6
			},
			{
				label: 'dwd表',
				value: 7
			},
			{
				label: 'dwd视图',
				value: 8
			},
			{
				label: '主数据派发',
				value: 9
			},
			{
				label: 'app',
				value: 10
			},
			{
				label: '其他',
				value: 99
			}
		],
		value: '',
		placeholder: '请选择节点类型'
	},
	{
		dataIndex: 'node_name',
		type: 'select',
		bind: {
			filterable: true,
			'allow-create': true
		},
		data: [],
		value: '',
		placeholder: '请选择节点名称'
	}
])

watch(
	() => condition[0].value,
	val => {
		if (val) {
			// axios
			// 	.get(`http://192.168.100.50:8109/api/data_lineage/node_name?node_type=${val}`)
			getNodeName(val)
				.then(res => {
					condition[1].data = res.data.map(v => {
						return {
							label: v.node_name,
							value: v.node_name,
							id: v.node_id
						}
					})
					condition[1].value = ''
				})
				.catch(err => {
					console.log(err)
					condition[1].data = []
					condition[1].value = ''
				})
		} else {
			condition[1].data = []
			condition[1].value = ''
		}
	}
)

const conditionSearch = () => {
	if (!condition[0].value) {
		ElMessage({
			message: '请选择节点类型',
			type: 'warning'
		})
		return
	} else if (!condition[1].value) {
		ElMessage({
			message: '请选择节点名称',
			type: 'warning'
		})
		return
	}

	const node = condition[1].data.find(v => {
		return condition[1].value === v.value
	})
	const node_id = node ? node.id : ''

	// axios
	// 	.get(`http://192.168.100.50:8109/api/data_lineage/graph?node_type=${condition[0].value}&node_name=${condition[1].value}&node_id=${node_id}`)
	getGraph({
		node_type: condition[0].value,
		node_name: condition[1].value,
		node_id: node_id
	}).then(res => {
		jsPlumb.deleteEveryConnection()

		json.nodes.map(v => {
			jsPlumb.setDraggable(v.key, false)
		})

		const data = res.data

		setPosInit(data.nodes)

		json.nodes = data.nodes.map(v => {
			v.key = 'tick' + tick + '_' + v.id
			tick++
			return v
		})
		json.relations = data.relations

		if (showRef.value) {
			showNodes.value = json.nodes.map(v => v.id)
		} else {
			showNodes.value = []
		}

		json.nodes = JSON.parse(JSON.stringify(json.nodes))

		nextTick(() => {
			addDraggable(json.nodes)

			finalConnect(json.nodes, json.relations)

			scaleSize.value = 1
			const content: any = document.getElementById('container')

			const instance = jsPlumb.getInstance({
				container: document.getElementById('container')
			})
			content.style.transform = `scale(${scaleSize.value})`
			instance.setZoom(scaleSize)
		})
	})
}
let showNodes = ref([])
const showRef = ref(false)

const showRefChange = value => {
	if (value) {
		showNodes.value = json.nodes.map(v => v.id)
	} else {
		showNodes.value = []
	}

	jsPlumb.deleteEveryConnection()

	nextTick(() => {
		finalConnect(json.nodes, json.relations)
	})
}

const nodeClick = item => {
	const i = showNodes.value.findIndex(v => v === item.id)

	if (i > -1) {
		showNodes.value.splice(i, 1)
	} else {
		showNodes.value.push(item.id)
	}

	if (showNodes.value.length === json.nodes.length) {
		showRef.value = true
	} else {
		showRef.value = false
	}

	const c = json.nodes.find(v => {
		return v.id === item.id
	})

	const step = c?.columns.loength * 18

	jsPlumb.deleteEveryConnection()

	nextTick(() => {
		finalConnect(json.nodes, json.relations)
	})
}

const instance = jsPlumb.getInstance({
	Connector: ['Bezier', { curviness: 50 }],
	Anchors: ['Right', 'Left'],
	Endpoint: ['Dot', { radius: 5 }],
	PaintStyle: { stroke: 'gray', strokeWidth: 2 },
	Container: 'container' // 设置连接线的容器
})

const scaleSize = ref(1)
onMounted(() => {
	getDatabaseList()

	jsPlumb.ready(function () {
		jsPlumb.setContainer('container')

		let currentTransform = { x: 0, y: 0 }
		nextTick(() => {
			const content: any = document.getElementById('container')

			const instance = jsPlumb.getInstance({
				container: document.getElementById('container')
			})
			content.style.transform = `scale(${scaleSize.value})`
			instance.setZoom(scaleSize)

			// 滚轮
			// 添加滚动监听器
			content.addEventListener('wheel', event => {
				event.preventDefault() // 阻止默认行为（可选）

				// 获取滚动的方向
				const delta = event.deltaY

				if (delta > 0) {
					if (scaleSize.value < 0.5) {
					} else {
						scaleSize.value -= 0.1
					}
					console.log('鼠标向下滚动')
				} else {
					if (scaleSize.value > 1.5) {
					} else {
						scaleSize.value += 0.1
					}
					console.log('鼠标向上滚动')
				}

				content.style.transform = `translate(${currentTransform.x}px, ${currentTransform.y}px) scale(${scaleSize.value})`
				instance.setZoom(scaleSize)
			})

			// 使用 interact.js 限制拖动在容器范围内
			interact('#container') // 假设每个节点元素都有 'draggable' 类
				.draggable({
					modifiers: [
						interact.modifiers.restrictRect({
							restriction: content, // 限制拖动在 container 内
							endOnly: true
						})
					],
					listeners: {
						move(event) {
							currentTransform.x += event.dx
							currentTransform.y += event.dy
							event.target.style.transform = `translate(${currentTransform.x}px, ${currentTransform.y}px) scale(${scaleSize.value})`
							instance.repaintEverything() // 强制 jsPlumb 重新渲染连接线
						}
					}
				})

			interact('.panel-node-origin') // 假设每个节点元素都有 'draggable' 类
				.draggable({
					modifiers: [
						interact.modifiers.restrictRect({
							restriction: content, // 限制拖动在 container 内
							endOnly: true
						})
					],
					listeners: {
						move(event) {
							// currentTransform.x += event.dx
							// currentTransform.y += event.dy
							// event.target.style.transform = `translate(${currentTransform.x}px, ${currentTransform.y}px)`
							instance.repaintEverything() // 强制 jsPlumb 重新渲染连接线
						}
					}
				})
		})

		// addDraggable(json.nodes)
		// finalConnect(json.nodes, json.relations)
	})
})

function setPosInit(nodes) {
	const source = []
	const middle1 = []
	const middle2 = []
	const target = []
	nodes.map(v => {
		if (v.type === 'source') {
			source.push(v)
		} else if (v.type === 'middle') {
			if (middle1.length > middle2.length) {
				middle2.push(v)
			} else {
				middle1.push(v)
			}
		} else if (v.type === 'target') {
			target.push(v)
		}
	})

	setPos(source, [100, 100 * 1 + 120 * 0], [100, 0])
	setPos(middle1, [50, 100 * 2 + 120 * 1], [100, 0])
	setPos(middle2, [100, 100 * 3 + 120 * 2], [100, 0])
	setPos(target, [150, 100 * 4 + 120 * 3], [100, 0])
}

function setPos(arr, [top, left], [t_step, l_step]) {
	arr.reduce(
		([t, l], c) => {
			c.top = t
			c.left = l
			const cTop = showNodes.value.includes(c.id) ? c.columns.length * 18 + 20 : 20
			return [t + t_step + cTop, l + l_step]
		},
		[top, left]
	)
}

function addDraggable(nodes) {
	nodes.map(v => {
		console.log(v.key)
		jsPlumb.setDraggable(v.key, true)
		jsPlumb.draggable(v.key, {
			containment: true,
			stop: conn => {
				const { el, pos } = conn
				v.top = pos[1]
				v.left = pos[0]
			}
		})
	})
}

function finalConnect(nodes, r) {
	let relations = relationsFliter(r)
	console.log(relations, 'relations')

	relations.map(relation => {
		let sourceId, targetId
		nodes.map(v => {
			if (v.id === relation.source.parentName) {
				sourceId = v.key
			} else if (v.id === relation.target.parentName) {
				targetId = v.key
			}
		})
		let nodeName
		if (showNodes.value.includes(relation.source.parentName)) {
			nodeName = sourceId + '.' + relation.source.column
		} else {
			nodeName = sourceId + '-heading'
		}

		let sourceUUID = nodeName
		let targetUUID
		if (showNodes.value.includes(relation.target.parentName)) {
			targetUUID = targetId + '.' + relation.target.column
		} else {
			targetUUID = targetId + '-heading'
		}

		console.log(sourceUUID, targetUUID)
		connectEndpoint(sourceUUID, targetUUID)
	})

	jsPlumb.unbind('mouseover')
	jsPlumb.bind('mouseover', function (conn, originalEvent) {
		console.log(conn)
		const source = conn.sourceId.includes('.') ? conn.sourceId.split('.') : conn.sourceId.split('-')
		const target = conn.targetId.includes('.') ? conn.targetId.split('.') : conn.targetId.split('-')
		// console.log(source, target, json.relations)
		const activeNodes = findNodes(
			json.relations,
			{
				parentName: source[0].split('_')[1],
				column: source[1]
			},
			{
				parentName: target[0].split('_')[1],
				column: target[1]
			}
		)

		const nodes = relationsFliter(activeNodes)

		nodes.map(node => {
			let sourceId, targetId
			json.nodes.map(v => {
				if (v.id === node.source.parentName) {
					sourceId = v.key
				} else if (v.id === node.target.parentName) {
					targetId = v.key
				}
			})

			if (node.source.column) {
				var sourceColumn = sourceId + '.' + node.source.column
			} else {
				var sourceColumn = sourceId + '-heading'
			}
			if (node.target.column) {
				var targetColumn = targetId + '.' + node.target.column
			} else {
				var targetColumn = targetId + '-heading'
			}

			jsPlumb
				.select({
					source: sourceColumn,
					target: targetColumn
				})
				.each(function (endpoint) {
					// console.log(endpoint.getPaintStyle())
					endpoint.setPaintStyle({
						strokeWidth: 2,
						stroke: 'black'
					})
				})

			json.nodes.find(v => {
				if (v.id === node.source.parentName && node.source.column) {
					v.columns.find(u => {
						if (u.name === node.source.column) {
							u.active = true
							console.log('1')
							return true
						}
					})
				}
				if (v.id === node.target.parentName && node.target.column) {
					v.columns.find(u => {
						if (u.name === node.target.column) {
							u.active = true
							console.log('2')
							return true
						}
					})
				}
			})
		})
	})

	jsPlumb.unbind('mouseout')
	jsPlumb.bind('mouseout', function (conn, originalEvent) {
		console.log(conn)
		const source = conn.sourceId.includes('.') ? conn.sourceId.split('.') : conn.sourceId.split('-')
		const target = conn.targetId.includes('.') ? conn.targetId.split('.') : conn.targetId.split('-')

		const activeNodes = findNodes(
			json.relations,
			{
				parentName: source[0].split('_')[1],
				column: source[1]
			},
			{
				parentName: target[0].split('_')[1],
				column: target[1]
			}
		)

		const nodes = relationsFliter(activeNodes)

		nodes.map(node => {
			let sourceId, targetId
			json.nodes.map(v => {
				if (v.id === node.source.parentName) {
					sourceId = v.key
				} else if (v.id === node.target.parentName) {
					targetId = v.key
				}
			})
			if (node.source.column) {
				var sourceColumn = sourceId + '.' + node.source.column
			} else {
				var sourceColumn = sourceId + '-heading'
			}
			if (node.target.column) {
				var targetColumn = targetId + '.' + node.target.column
			} else {
				var targetColumn = targetId + '-heading'
			}
			jsPlumb
				.select({
					source: sourceColumn,
					target: targetColumn
				})
				.each(function (endpoint) {
					console.log(endpoint.getPaintStyle())
					endpoint.setPaintStyle({
						strokeWidth: 2,
						stroke: '#c4c4c4'
					})
				})
		})
		json.nodes.map(v => {
			v.columns.map(u => {
				u.active = false
			})
		})
	})
}

function loop(relations, item, arrow) {
	if (arrow === 'left') {
		const s = relations.filter(v => {
			return v.target.parentName === item.parentName && v.target.column === item.column && item.column
		})
		if (s.length) {
			return s.concat(loop(relations, s[0].source, 'left'))
		} else {
			return []
		}
	} else {
		const s = relations.filter(v => {
			return v.source.parentName === item.parentName && v.source.column === item.column && item.column
		})
		if (s.length) {
			return s.concat(loop(relations, s[0].target, 'right'))
		} else {
			return []
		}
	}
}

function findNodes(relations, source, target) {
	const i = {
		source,
		target
	}
	if (source.column === 'heading' && target.column === 'heading') {
		return [i]
	} else if (source.column === 'heading') {
		const item = json.relations.find(v => {
			return v.target.column === target.column && v.target.parentName === target.parentName
		})
		i.source = item.source
	} else if (target.column === 'heading') {
		const item = json.relations.find(v => {
			return v.source.column === source.column && v.source.parentName === source.parentName
		})
		i.target = item.target
	}

	const left = loop(json.relations, i.source, 'left')
	const right = loop(json.relations, i.target, 'right')

	return [...left, i, ...right]
}

function connectEndpoint(from, to) {
	const common = visoConfig.baseStyle
	jsPlumb.connect(
		{
			source: from,
			target: to,
			anchor: ['Left', 'Right'],
			connector: ['StateMachine']
		},
		common
	)
}

function relationsFliter(arr) {
	let arr2 = arr.map(v => {
		let obj = {
			source: {
				parentName: '',
				column: ''
			},
			target: {
				parentName: '',
				column: ''
			}
		}
		if (showNodes.value.includes(v.source.parentName)) {
			obj.source.column = v.source.column
			obj.source.parentName = v.source.parentName
		} else {
			obj.source.column = ''
			obj.source.parentName = v.source.parentName
		}
		if (showNodes.value.includes(v.target.parentName)) {
			obj.target.column = v.target.column
			obj.target.parentName = v.target.parentName
		} else {
			obj.target.column = ''
			obj.target.parentName = v.target.parentName
		}
		return JSON.stringify(obj)
	})
	let set = new Set(arr2)
	return Array.from(set).map(v => JSON.parse(v))
}

function getDatabaseList() {
	listDatabase().then(res => {
		const item = DialogData.value.find(v => v.dataIndex === 'target_database_id')

		item.data = res.data.map(v => {
			return {
				label: v.name,
				value: v.id
			}
		})
	})
}

const Dialog = ref({
	title: '添加下级节点',
	visible: false,
	loading: false
})

const DialogFormRef = ref(null)

const DialogState = ref({
	source_node_id: '',
	target_database_id: '',
	target_node_type: '',
	target_node_name: ''
})

watch(
	() => DialogState.value.target_node_type,
	val => {
		if (val) {
			// axios
			// 	.get(`http://192.168.100.50:8109/api/data_lineage/node_name?node_type=${val}`)
			getNodeName(val)
				.then(res => {
					DialogData.value[2].data = res.data.map(v => {
						return {
							label: v.node_name,
							value: v.node_name
						}
					})
					DialogState.value.target_node_name = ''
				})
				.catch(err => {
					DialogData.value[2].data = []
					DialogState.value.target_node_name = ''
				})
		} else {
			DialogData.value[2].data = []
			DialogState.value.target_node_name = ''
		}
	}
)

const DialogData = ref([
	{
		title: '数据库连接',
		dataIndex: 'target_database_id',
		type: 'select',
		data: []
	},
	{
		title: '节点类型',
		dataIndex: 'target_node_type',
		type: 'select',
		data: condition[0].data,
		rules: [{ required: true, message: '请选择所属分类', trigger: 'change' }]
	},
	{
		title: '节点名称',
		dataIndex: 'target_node_name',
		type: 'select',
		bind: {
			filterable: true,
			'allow-create': true
		},
		data: [],
		rules: [{ required: true, message: '请输入节点名称', trigger: 'blur' }]
	}
])

const DialogReset = (item: any) => {
	const obj = {
		source_node_id: '',
		target_database_id: '',
		target_node_type: '',
		target_node_name: ''
	}
	if (item) {
		DialogState.value = { ...obj, ...item }
	} else {
		DialogState.value = { ...obj }
	}
}

const DialogShow = item => {
	const { id } = item
	DialogFormRef.value && DialogFormRef.value.reset()
	DialogReset({
		source_node_id: id
	})
	Dialog.value.visible = true
}

const DialogSave = async () => {
	try {
		Dialog.value.loading = true
		await DialogFormRef.value.submit()
		let params = {
			...DialogState.value
		}

		// axios.post('http://192.168.100.50:8109/api/data_lineage/add_next_link', params)
		addNextLink(params)
			.then((res: any) => {
				if (res.code === 0) {
					ElMessage({
						message: '新增成功',
						type: 'success'
					})
					Dialog.value.loading = false
					Dialog.value.visible = false
					conditionSearch()
				} else {
					ElMessage({
						message: res.msg,
						type: 'error'
					})
					Dialog.value.loading = false
				}
			})
			.catch(() => {
				Dialog.value.loading = false
			})
	} catch (e) {
		Dialog.value.loading = false
		console.log(e)
	}
}

let json = reactive({
	relations: [],
	nodes: []
})

// let json = reactive({
// 	relations: [
// 		{
// 			source: {
// 				column: 'name',
// 				parentName: 'data2'
// 			},
// 			target: {
// 				column: 'name',
// 				parentName: 'middle1'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'name',
// 				parentName: 'data1'
// 			},
// 			target: {
// 				column: 'name',
// 				parentName: 'middle2'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'age',
// 				parentName: 'data1'
// 			},
// 			target: {
// 				column: 'age',
// 				parentName: 'middle1'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'age',
// 				parentName: 'data2'
// 			},
// 			target: {
// 				column: 'age',
// 				parentName: 'middle2'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'class',
// 				parentName: 'data1'
// 			},
// 			target: {
// 				column: 'class',
// 				parentName: 'middle2'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'grade',
// 				parentName: 'data2'
// 			},
// 			target: {
// 				column: 'grade',
// 				parentName: 'middle2'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'age',
// 				parentName: 'middle1'
// 			},
// 			target: {
// 				column: 'age',
// 				parentName: 'middle3'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'name',
// 				parentName: 'middle2'
// 			},
// 			target: {
// 				column: 'name',
// 				parentName: 'middle3'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'class',
// 				parentName: 'middle2'
// 			},
// 			target: {
// 				column: 'class',
// 				parentName: 'middle3'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'grade',
// 				parentName: 'middle2'
// 			},
// 			target: {
// 				column: 'grade',
// 				parentName: 'middle3'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'name',
// 				parentName: 'middle3'
// 			},
// 			target: {
// 				column: 'name',
// 				parentName: 'RS'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'age',
// 				parentName: 'middle3'
// 			},
// 			target: {
// 				column: 'age',
// 				parentName: 'RS'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'grade',
// 				parentName: 'middle3'
// 			},
// 			target: {
// 				column: 'grade',
// 				parentName: 'RS'
// 			}
// 		},
// 		{
// 			source: {
// 				column: 'class',
// 				parentName: 'middle3'
// 			},
// 			target: {
// 				column: 'class',
// 				parentName: 'RS'
// 			}
// 		}
// 	],
// 	nodes: [
// 		{
// 			id: 'data1',
// 			name: 'data1',
// 			type: 'source',
// 			columns: [
// 				{
// 					name: 'age'
// 				},
// 				{
// 					name: 'name'
// 				},
// 				{
// 					name: 'class'
// 				}
// 			],
// 			top: 155,
// 			left: 50
// 		},
// 		{
// 			id: 'data2',
// 			name: 'data2',
// 			type: 'source',
// 			columns: [
// 				{
// 					name: 'age'
// 				},
// 				{
// 					name: 'name'
// 				},
// 				{
// 					name: 'grade'
// 				}
// 			],
// 			top: 255,
// 			left: 50
// 		},
// 		{
// 			id: 'middle1',
// 			name: 'middle1',
// 			type: 'middle',
// 			columns: [
// 				{
// 					name: 'age'
// 				},
// 				{
// 					name: 'name'
// 				}
// 			],
// 			top: 139,
// 			left: 233
// 		},
// 		{
// 			id: 'middle2',
// 			name: 'middle2',
// 			type: 'middle',
// 			columns: [
// 				{
// 					name: 'age'
// 				},
// 				{
// 					name: 'name'
// 				},
// 				{
// 					name: 'class'
// 				},
// 				{
// 					name: 'grade'
// 				}
// 			],
// 			top: 309,
// 			left: 281
// 		},
// 		{
// 			id: 'middle3',
// 			name: 'middle3',
// 			type: 'middle',
// 			columns: [
// 				{
// 					name: 'age'
// 				},
// 				{
// 					name: 'name'
// 				},
// 				{
// 					name: 'class'
// 				},
// 				{
// 					name: 'grade'
// 				}
// 			],
// 			top: 222,
// 			left: 388
// 		},
// 		{
// 			id: 'RS',
// 			name: 'RS',
// 			type: 'target',
// 			columns: [
// 				{
// 					name: 'age'
// 				},
// 				{
// 					name: 'name'
// 				},
// 				{
// 					name: 'class'
// 				},
// 				{
// 					name: 'grade'
// 				}
// 			],
// 			top: 280,
// 			left: 571
// 		}
// 	]
// })

const colMouseEnter = async (item, col) => {
	const data: any = await findConnentCol(col.name, json.relations, item.id)
	console.log(data)
	data.map(node => {
		let sourceId, targetId
		json.nodes.map(v => {
			if (v.id === node.source.parentName) {
				sourceId = v.key
			} else if (v.id === node.target.parentName) {
				targetId = v.key
			}
		})
		if (node.source.column) {
			var sourceColumn = sourceId + '.' + node.source.column
		} else {
			var sourceColumn = sourceId + '-heading'
		}
		if (node.target.column) {
			var targetColumn = targetId + '.' + node.target.column
		} else {
			var targetColumn = targetId + '-heading'
		}
		console.log(sourceColumn, targetColumn)
		jsPlumb
			.select({
				source: sourceColumn,
				target: targetColumn
			})
			.each(function (endpoint) {
				console.log(endpoint.getPaintStyle())
				endpoint.setPaintStyle({
					strokeWidth: 2,
					stroke: 'black'
				})
			})
	})
}
const colMouseLeave = async (item, col) => {
	const data: any = await findConnentCol(col.name, json.relations, item.id)
	console.log(data)
	data.map(node => {
		let sourceId, targetId
		json.nodes.map(v => {
			if (v.id === node.source.parentName) {
				sourceId = v.key
			} else if (v.id === node.target.parentName) {
				targetId = v.key
			}
		})
		if (node.source.column) {
			var sourceColumn = sourceId + '.' + node.source.column
		} else {
			var sourceColumn = sourceId + '-heading'
		}
		if (node.target.column) {
			var targetColumn = targetId + '.' + node.target.column
		} else {
			var targetColumn = targetId + '-heading'
		}
		console.log(sourceColumn, targetColumn)
		jsPlumb
			.select({
				source: sourceColumn,
				target: targetColumn
			})
			.each(function (endpoint) {
				console.log(endpoint.getPaintStyle())
				endpoint.setPaintStyle({
					strokeWidth: 2,
					stroke: '#c4c4c4'
				})
			})
	})
}

const findConnentCol = (name, data, parentName) => {
	let connectData: any = []
	console.log(data)

	// 先找到相同的source数据
	const someSourceData = data.filter(item => {
		return item.source.column === name && item.source.parentName === parentName
	})

	const secSourceData: any = []
	if (someSourceData) {
		someSourceData.forEach(item => {
			data.forEach(v => {
				if (v.source.column === item.target.column && v.source.parentName === item.target.parentName) {
					secSourceData.push(v)
				}
			})
		})
	}

	// 找相同target数据
	const someTargetData = data.filter(item => {
		return item.target.column === name && item.target.parentName === parentName
	})

	const preTargetData: any = []
	if (someTargetData) {
		someTargetData.forEach(item => [
			data.forEach(v => {
				if (v.target.column === item.source.column && v.target.parentName === item.source.parentName) {
					preTargetData.push(v)
				}
			})
		])
	}

	// console.log(someSourceData, someTargetData)

	// const getData = (name, data, parentName) => {
	// if (parentName.split('_')[0] != 'middle' || parentName.split('_')[0] != 'target')
	// 	data.map(item => {
	// 		if (item.source.column === name && item.source.parentName === parentName) {
	// 			connectData.push(item)
	// 			getData(item.target.column, data, item.target.parentName)
	// 		}
	// 	})
	// }
	// await getData(name, data, parentName)
	connectData = [...someSourceData, ...someTargetData, ...secSourceData, ...preTargetData]
	return connectData
}
</script>

<template>
	<div>
		<el-card class="card">
			<Condition v-model:condition="condition" :btns="['search']" @search="conditionSearch"> </Condition>
			<el-form inline>
				<el-form-item label="表字段">
					<el-switch v-model="showRef" @input="showRefChange" />
				</el-form-item>
			</el-form>
			<div class="container-box" style="width: 100%; height: calc(100vh - 268px); overflow: hidden">
				<div id="container">
					<template v-for="item in json.nodes" :key="item.key">
						<template v-if="item.type === 'source'">
							<div :id="item.key" class="pa" :style="{ top: item.top + 'px', left: item.left + 'px' }">
								<div :id="item.key + '-inner'" class="panel panel-node panel-node-origin">
									<div :id="item.key + '-heading'" class="table-header" :data-id="item.key + '-heading'">
										<el-tooltip class="box-item" effect="dark" :content="item.id">
											<div class="title">
												{{ item.name }}
											</div>
										</el-tooltip>
										<div class="icons">
											<el-icon @click.stop="DialogShow(item)"><Plus /></el-icon>
											<el-icon @click.stop="nodeClick(item)"><ArrowDown /></el-icon>
										</div>
									</div>
									<ul v-if="showNodes.includes(item.id)" :id="item.id + '-cols'" class="col-group">
										<li
											v-for="col in item.columns"
											:id="item.key + '.' + col.name"
											:key="col.name"
											:class="{ active: col.active }"
											class="panel-node-list"
											@mouseenter.native="colMouseEnter(item, col)"
											@mouseleave.native="colMouseLeave(item, col)"
										>
											{{ col.name }}
										</li>
									</ul>
								</div>
							</div>
						</template>
						<template v-else-if="item.type === 'middle'">
							<div :id="item.key" class="pa" :style="{ top: item.top + 'px', left: item.left + 'px' }">
								<div :id="item.key + '-inner'" class="panel panel-node panel-node-origin">
									<div
										:id="item.key + '-heading'"
										class="table-header"
										:data-id="item.key + '-heading'"
										style="background-color: #dfc6a8; color: white"
									>
										<el-tooltip class="box-item" effect="dark" :content="item.id">
											<div class="title">
												{{ item.name }}
											</div>
										</el-tooltip>
										<div class="icons">
											<el-icon @click.stop="DialogShow(item)"><Plus /></el-icon>
											<el-icon @click.stop="nodeClick(item)"><ArrowDown /></el-icon>
										</div>
									</div>
									<ul v-if="showNodes.includes(item.id)" :id="item.id + '-cols'" class="col-group">
										<li
											v-for="col in item.columns"
											:id="item.key + '.' + col.name"
											:key="col.name"
											:class="{ active: col.active }"
											class="panel-node-list"
											@mouseenter.native="colMouseEnter(item, col)"
											@mouseleave.native="colMouseLeave(item, col)"
										>
											{{ col.name }}
										</li>
									</ul>
								</div>
							</div>
						</template>
						<template v-else-if="item.type === 'UNION'">
							<div :id="item.key" class="pa" :style="{ top: item.top + 'px', left: item.left + 'px' }">
								<div :id="item.key + '-inner'" class="panel panel-node panel-node-origin">
									<div
										:id="item.key + '-heading'"
										class="table-header"
										:data-id="item.key + '-heading'"
										style="background-color: #66ccff; color: white"
									>
										<el-tooltip class="box-item" effect="dark" :content="item.id">
											<div class="title">
												{{ item.name }}
											</div>
										</el-tooltip>
										<div class="icons">
											<el-icon @click.stop="DialogShow(item)"><Plus /></el-icon>
											<el-icon @click.stop="nodeClick(item)"><ArrowDown /></el-icon>
										</div>
									</div>
									<ul v-if="showNodes.includes(item.id)" :id="item.id + '-cols'" class="col-group">
										<li
											v-for="col in item.columns"
											:id="item.key + '.' + col.name"
											:key="col.name"
											:class="{ active: col.active }"
											class="panel-node-list"
											@mouseenter.native="colMouseEnter(item, col)"
											@mouseleave.native="colMouseLeave(item, col)"
										>
											{{ col.name }}
										</li>
									</ul>
								</div>
							</div>
						</template>
						<template v-else-if="item.type === 'target'">
							<div :id="item.key" class="pa" :style="{ top: item.top + 'px', left: item.left + 'px' }">
								<div :id="item.key + '-inner'" class="panel panel-node panel-node-origin">
									<div
										:id="item.key + '-heading'"
										class="table-header"
										:data-id="item.key + '-heading'"
										style="background-color: #ff9900; color: white"
									>
										<el-tooltip class="box-item" effect="dark" :content="item.id">
											<div class="title">
												{{ item.name }}
											</div>
										</el-tooltip>
										<div class="icons">
											<el-icon @click.stop="DialogShow(item)"><Plus /></el-icon>
											<el-icon @click.stop="nodeClick(item)"><ArrowDown /></el-icon>
										</div>
									</div>
									<ul v-if="showNodes.includes(item.id)" :id="item.id + '-cols'" class="col-group">
										<li
											v-for="col in item.columns"
											:id="item.key + '.' + col.name"
											:key="col.name"
											:class="{ active: col.active }"
											class="panel-node-list"
											@mouseenter.native="colMouseEnter(item, col)"
											@mouseleave.native="colMouseLeave(item, col)"
										>
											{{ col.name }}
										</li>
									</ul>
								</div>
							</div>
						</template>
					</template>
				</div>
			</div>
		</el-card>
		<el-dialog v-model="Dialog.visible" :title="Dialog.title">
			<Form ref="DialogFormRef" :form-state="DialogState" :form-data="DialogData"></Form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="Dialog.visible = false">取 消</el-button>
					<el-button type="primary" :loading="Dialog.loading" @click="DialogSave">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<style scoped lang="scss">
.card {
	min-height: calc(100vh - 70px - var(--theme-header-height));
	//::v-deep(.el-card__body) {
	//	height: 100%;
	//	box-sizing: border-box;
	//}
}
#container {
	width: 100%;
	height: 2000px;
	background-color: #dff0d8;
	position: relative;
}

.add,
.icon {
	cursor: pointer;
}

.label {
	line-height: 14px;
	font-size: 14px;
	color: black;
	cursor: pointer;
}

#checkbox {
	margin: 0;
	cursor: pointer;
}

.pa {
	position: absolute;
	width: 120px;
}

.col-group {
	padding-left: 0;
	margin-bottom: 0;
	line-height: 1.2;
	width: 100%;
}

.col-group-item {
	border: 1px solid #ddd;
	position: relative;
	display: block;
}

.panel-node {
	display: inline-block;
	// 宽度内容希望自适应
	// width: 120px;
	/*行内文本太长后面的就省略*/
}

.panel-node-origin {
	border: 1px solid #91c051;
	background-color: #91c051;
}

.panel-node-middle {
	border: 1px solid #dfc6a8;
	background-color: #dfc6a8;
}

.panel-node-union {
	border: 1px solid #66ccff;
	background-color: #66ccff;
}

.panel-node-rs {
	border: 1px solid #ff9900;
	background-color: #ff9900;
}

.table-header {
	box-sizing: border-box;
	// width: 120px;
	padding: 1px 5px;
	background-color: #91c051;
	color: white;
	font-size: 12px;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
	.title {
		// 宽度自适应
		width: auto;
		// width: 100px;
		// text-overflow: ellipsis;
		// overflow: hidden;
		white-space: nowrap;
	}
	.icons {
		display: flex;
		flex-direction: row;
		align-items: center;
		flex-wrap: nowrap;
		font-size: 18px;
	}
}

.panel-node-list {
	background-color: #fff;
	padding: 2px 5px;
	font-size: smaller;
	/*行内文本太长后面的就省略*/
	text-overflow: ellipsis;
	overflow: hidden;
	white-space: nowrap;
}

.panel-node-list:hover {
	background-color: #faebd7;
}

.active {
	background-color: #faebd7;
}
</style>
